const builder = require('farris-themebuilder/themebuilder/src/modules/builder');
const { metadata } = require('farris-themebuilder/themebuilder/src/data/metadata/farris-theme-builder-metadata');
const baseParameters = require('farris-themebuilder/themebuilder/src/modules/base-parameters');
const themes = require('farris-themebuilder/themebuilder/src/modules/themes').default;
const { version } = require('farris-themebuilder/themebuilder/src/package.json');
const bodyParser = require('body-parser');
const cors = require('cors');
const compression = require('compression');
const express = require('express');

const app = express();

app.use(cors());
app.use(compression());
app.use(bodyParser.json({limit: '2mb'}));
app.use(
    bodyParser.urlencoded({
        extended: true
    })
);

function createMetadata() {
    const result = metadata;

    if (themes) {
        result.themes = themes;
    }

    if (version) {
        result.version = version;
    }

    if (baseParameters) {
        result.baseParameters = baseParameters;
    }

    return result;
}

const currentMetadata = createMetadata();

app.options('*', cors());

app.get('/metadata', (req, res) => {
    if (!currentMetadata) res.status(500).send({ err: 'No metadata' });

    res.status(200).send(currentMetadata);
});

app.post('/buildtheme', (req, res) => {
    builder.buildTheme(req.body).then(
        (result) => {
            res.json(result);
        },
        (err) => {
            res.status(500).send(err);
        }
    );
});
app.listen(3000);
console.log(`Open http://localhost:3000`);
